package com.lanyou.cook.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lanyou.cook.entity.domain.DataDictionaryValue;
import com.lanyou.cook.repository.DataDictionaryValueRepository;

@Component
public class DataDictionaryService implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
	
	@Autowired
	private DataDictionaryValueRepository dataDictionaryValueRepository;
	
	private LoadingCache<String, String> valueNameCache = CacheBuilder.newBuilder().build(new CacheLoader<String, String>() {
		public String load(String key) {
			String[] params = StringUtils.split(key, '.');
			String typeCode = params[0];
			String valueCode = params[1];
			DataDictionaryValue entity = dataDictionaryValueRepository.findById_TypeCodeAndId_ValueCode(typeCode,
					valueCode);
			return entity.getValueName();
		}
	});
	
	public static DataDictionaryService getInstance(){
		return applicationContext.getBean(DataDictionaryService.class);
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		DataDictionaryService.applicationContext = applicationContext;
	}
	
	public String getValueName(String typeCode, String valueCode){
		try {
			return valueNameCache.get(String.format("%s.%s", typeCode, valueCode));
		} catch (Exception e) {
			return null;
		}
	}
	
	
}
